package com.symaster.gameengine.e2d.transform;

import com.symaster.gameengine.core.Component;
import com.symaster.gameengine.core.FrameCall;
import com.symaster.gameengine.geom.Vector;
import org.lwjgl.glfw.GLFW;

/**
 * @author yinmiao
 * @version 2023/11/16
 */
public class TransformMove extends Component implements FrameCall {

    /**
     * 设定每秒移动距离
     */
    private float speed = 0f;
    /**
     * 输入向量
     */
    private Vector input;
    /**
     * 移动目标Transform组件
     */
    private Transform operate;
    /**
     * 移动向量
     */
    private final Vector moveVictor = new Vector();

    private Double lastTime;

    public Vector getMoveVictor() {
        return moveVictor;
    }

    public Transform getOperate() {
        return operate;
    }

    public void setOperate(Transform operate) {
        this.operate = operate;
    }

    public Vector getInput() {
        return input;
    }

    public void setInput(Vector input) {
        this.input = input;
    }

    public float getSpeed() {
        return speed;
    }

    public void setSpeed(float speed) {
        this.speed = speed;
    }

    @Override
    public void update(long window) {
        if (input == null || operate == null) {
            return;
        }

        // 获取到当前速度(每秒移动速度)
        double speed = Math.min(input.length(), 1) * this.speed;

        if (lastTime != null && speed > 0.0001f) {
            // 时间间隔(秒)
            double timeInterval = GLFW.glfwGetTime() - lastTime;

            // 设置角度
            operate.setAngle((float) input.angleFromUp());
            moveVictor.setX(input.getX());
            moveVictor.setY(input.getY());
            moveVictor.normalize();
            moveVictor.mul(timeInterval * speed);

        } else {
            moveVictor.setX(0);
            moveVictor.setY(0);
        }

        operate.xAdd((float) moveVictor.getX());
        operate.yAdd((float) moveVictor.getY());
        lastTime = GLFW.glfwGetTime();
    }

}
